<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMAPIDocumentationController extends DMAbstractController {

	public function index() {
		// load main documentation XML file
		$dxml = new DMDOMDocument("1.0", "utf-8");
		$dxml->load(dirname(__FILE__) . "/../../includes/doc/1/index.xml");

		// append XML fragments from module documentation files
		$mm = DMModuleManager::getInstance();
		foreach ($mm->getEnabledModules() as $module) {
			$module_dxml = $module->getHTTPAPIDocumentation();
			if (!$module_dxml) {
				continue;
			}
			$module_dxp = new DOMXPath($module_dxml);
			foreach ($dxml->documentElement->getElementsByTagName("category")
					as $main_cat) {
				$main_cat_name = $main_cat->getAttribute("name");
				$matching_module_methods = $module_dxp->query(
						sprintf("//category[@name = '%s']/apiMethod",
								$main_cat_name));
				foreach ($matching_module_methods as $method_node) {
					$new_node = $dxml->importNode($method_node, true);
					$main_cat->appendChild($new_node);
				}
			}
		}

		// apply XSL stylesheet
		$dxsl = new DOMDocument();
		$dxsl->load(dirname(__FILE__) . "/../../includes/doc/1/default.xsl",
				LIBXML_NOCDATA);
		$xslt = new XSLTProcessor();
		$xslt->importStylesheet($dxsl);
		$uri = DMHTTPRequest::getCurrent()->getURI();
		$uri->setFragment(null);
		$uri->setQueryString(null);
		$uri->setExtension(null);
		$uri->setParams(null);
		$xslt->setParameter(null, "dmBridgeURI", $uri);
		$doc = $xslt->transformToDoc($dxml);

		// append CSS stylesheet
		$style = $doc->createElement("link");
		$style->setAttribute("rel", "stylesheet");
		$style->setAttribute("href",
				dirname($_SERVER['PHP_SELF']) . "/includes/doc/1/default.css");
		$dxp = new DOMXPath($doc);
		$result = $dxp->query("//html/head");
		$result->item(0)->appendChild($style);

		$response = new DMHTTPResponse();
		$rep = new DMHTTPRepresentation();
		$rep->setMediaType(new DMMediaType("text", "html"));
		$doc->formatOutput = true;
		$rep->setBody('<!DOCTYPE html>' . $doc->saveHTML());
		$response->setRepresentation($rep);
		$response->send();
		die;
	}

}
